package com.app.business.web.business;

import com.app.business.en.Status;
import com.app.business.model.Contract;
import com.app.business.service.ActionHistoryService;
import com.app.business.service.ContractService;
import com.app.system.jpa.PageBean;
import com.app.system.log4j2.LogUtils;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.IntegerUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 档案发放
 * Created by ddz on 2019/7/6.
 *
 * @author ddz
 */
@Controller
@RequestMapping("/business/daff/*")
@SuppressWarnings("all")
public class DaffController {

    @Autowired
    private ContractService contractService;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private ActionHistoryService actionHistoryService;

    private Logger logger = LogUtils.getBusinessLogger();
    @Autowired
    private Configuration freemarkerConfiguration; // 注入bean，这里是属性注入，推荐构造注入

    /**
     * 档案发放管理列表
     */
    @RequestMapping("daffList")
    @RequiresPermissions("daff:daffList")
    public void list() {
    }

    /**
     * 加载档案发放数据管理列表
     *
     * @return
     */
    @RequestMapping("loadDaffList")
    @ResponseBody
    @RequiresPermissions("daff:loadDaffList")
    public Map loadContractList() {
        List<Map> listData = Lists.newArrayList();
        PageBean<Contract> contractPageBean = this.contractService.getAzSignAndFhPageBean();
        List<Contract> contractList = contractPageBean.getDatas();
        Map<String, DataDict> signMap = this.dataDictService.getMapByParentNameForValue("签约状态");
        Map<String, DataDict> settleMap = this.dataDictService.getMapByParentNameForValue("财务结清状态");
        Map<String, DataDict> daffMap = this.dataDictService.getMapByParentNameForValue("档案发放状态");
        Map<String, DataDict> takeHouseMap = this.dataDictService.getMapByParentNameForValue("交房状态");
        Map<String, DataDict> townMap = this.dataDictService.getMapByParentNameForValue("乡镇");
        if (!CollectionUtils.isEmpty(contractList)) {
            Map<String, Object> item = null;
            for (Contract contract : contractList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", contract.getId());
                item.put("town", StringUtils.dataDictShow(townMap.get(contract.getZsProject().getTown())));
                item.put("zsProjectName", contract.getZsProject().getProjectName());
                item.put("contractCode", StringUtils.getNotNull(contract.getContractCode()));
                item.put("name", StringUtils.getNotNull(contract.getName()));
                item.put("chooseHouseNum", StringUtils.getNotNull(contract.getChooseHouseNum()));
                item.put("limitHouseAreaTotal", BigDecimalUtils.getNotNullStr(contract.getLimitHouseAreaTotal()));
                item.put("financeSettleStatus", IntegerUtils.getNotNull(contract.getFinanceSettleStatus()));
                item.put("financeSettleStatusStr", StringUtils.dataDictShow(settleMap.get(IntegerUtils.getNotNull(contract.getFinanceSettleStatus()).toString())));
                item.put("azSignStatus", IntegerUtils.getNotNull(contract.getAzSignStatus()));
                item.put("azSignStatusStr", StringUtils.dataDictShow(signMap.get(IntegerUtils.getNotNull(contract.getAzSignStatus()).toString())));
                item.put("takeHouseStatus", IntegerUtils.getNotNull(contract.getTakeHouseStatus()));
                item.put("daffDate", DateUtils.dateToStringFormat(contract.getDaffDate(),"yyyy-MM-dd"));
                item.put("takeHouseStatusStr", StringUtils.dataDictShow(takeHouseMap.get(IntegerUtils.getNotNull(contract.getTakeHouseStatus()).toString())));
                item.put("daffStatus", IntegerUtils.getNotNull(contract.getDaffStatus()));
                item.put("daffStatusStr", StringUtils.dataDictShow(daffMap.get(IntegerUtils.getNotNull(contract.getDaffStatus()).toString())));
                listData.add(item);
            }
        }
        return LayUiUtils.page(contractPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 设置档案状态（可撤销）
     *
     * @param request
     */
    @RequestMapping("setDaffStatus")
    @ResponseBody
    @RequiresPermissions("daff:setDaffStatus")
    public synchronized Response setDaffStatus(HttpServletRequest request) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        String str = null;
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        if (contract.getFinalMoney().compareTo(new BigDecimal("0")) < 0) {
            Precondition.checkAjaxArguement(contract.getFinanceSettleStatus().equals(Status.YES.getIndex()), "2222", "该家庭尚未结清款项，不允许改变状态！");
        }
        if (contract.getDaffStatus().equals(Status.NO.getIndex())) {
            contract.setDaffStatus(Status.YES.getIndex());
            contract.setDaffDate(new Date());
            contract.setTakeHouseStatus(Status.YES.getIndex());
            contract.setTakeHouseDate(new Date());
            str = "设置为档案已发放，已交房";
        } else {
            contract.setDaffStatus(Status.NO.getIndex());
            contract.setDaffDate(null);
            contract.setTakeHouseStatus(Status.NO.getIndex());
            contract.setTakeHouseDate(null);
            str = "设置为档案未发放，未交房";
        }
        this.contractService.save(contract);
        this.actionHistoryService.saveActionHistoryByContractId(contract.getId(), str, "档案发放状态");

        return new Response("0001", "操作成功");
    }
}
